from RandomList import GetRandomList
import timeit
# 冒泡排序
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        # Last i elements are already in place
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1] :
                arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr

def bubble_sort_opt(arr):
    # 优化j的缩进步长，并不会改变复杂度
    n = len(arr)
    j = n - 1
    flag = True  
    while flag and j > 0:
        flag = False  
        k = j - 1  
        for i in range(j):  
            if arr[i] > arr[i+1]:
                flag = True  
                arr[i], arr[i+1] = arr[i+1], arr[i]
                k = i 
        j = k  
    return arr





    
if __name__ == '__main__':
    Arr = GetRandomList(500)
    print("bubble Sort Running Time is " + str(round(timeit.timeit(lambda :bubble_sort(Arr), number = 1) * 1000, 3 )) + " ms")
    Arr = GetRandomList(500)
    print("bubblt Sort opt Running Time is " + str(round(timeit.timeit(lambda :bubble_sort_opt(Arr), number = 1) * 1000, 3 )) + " ms")
